import React, { createContext, useContext, useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { type RemediationItem, RemediationStatus, type RemediationFilters, type RemediationStats, type RemediationFormData } from '@/types/Remediation';
import { type ComplianceItem, ProgressStatus, RiskLevel } from '@/types/work';
import { type AssessmentType } from '@/types/business';
import { getRemediationItems, addRemediationItem, updateRemediationItem, deleteRemediationItem, toggleRemediationStatus, createFromComplianceItem as createFormData } from '@/api/remediation';
import { exportRemediationItemsToReport, getAssessmentTypeName,sortComplianceItems} from '@/utils/utils';
import { useComplianceStore } from '@/stores/useComplianceStore';
import { showMessage } from '@/components/common/MessageTip';


// 定义上下文类型
interface RemediationContextType {
  // 数据
  remediationItems: RemediationItem[];  
  pendingComplianceItems: ComplianceItem[];
  stats: RemediationStats;
  
  // 筛选
  filters: RemediationFilters;
  
  setFilters: (filters: Partial<RemediationFilters>) => void;
  filteredItems: RemediationItem[];
  
  // 加载特定计划的整改项
  loadRemediationItems: (planId: string) => Promise<void>;
  
  // CRUD 操作
  addRemediationItem: (data: RemediationFormData) => Promise<RemediationItem | null>;
  updateRemediationItem: (id: string, updates: Partial<RemediationItem>) => Promise<RemediationItem | undefined>;
  deleteRemediationItem: (id: string) => Promise<boolean | undefined>;
  toggleStatus: (id: string) => Promise<RemediationItem | undefined>;
  
  // 从检查项创建整改项
  createFromComplianceItem: (complianceItem: ComplianceItem, plan_id: string) => RemediationFormData;
  
  // 导出报告
  exportReport: () => void;
  
  // 加载状态
  isLoading: boolean;
  error: Error | null;
}

// 创建上下文
const RemediationContext = createContext<RemediationContextType | undefined>(undefined);

// 当前活动的评估计划ID将作为属性传入

/**
 * 整改台账上下文提供者组件
 */
interface RemediationProviderProps {
  children: React.ReactNode;
  complianceItems?: any[]; // 使用更具体的类型替换 any，添加可选标记
  planId?: string; // 评估计划ID，可选
  businessName?: string; // 业务名称，可选
  assessmentType?: AssessmentType; // 评估类型，可选
}

export const RemediationProvider: React.FC<RemediationProviderProps> = ({ 
  children,
  planId,
  businessName,
  assessmentType
}) => {
  // 状态
  const [remediationItems, setRemediationItems] = useState<RemediationItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);
  const [filters, setFilters] = useState<RemediationFilters>({
    status: 'all',
    riskLevel: 'all',
    searchTerm: '',
  });
  
  // 使用useComplianceStore获取complianceItems
  const { items: complianceItems } = useComplianceStore();
  
  // 缓存相关状态
  const cache = useRef<Record<string, RemediationItem[]>>({});
  const [lastFetchTime, setLastFetchTime] = useState<number>(0);
  const FETCH_INTERVAL = 5 * 60 * 1000; // 5分钟

  // 加载特定计划的整改项数据
  const loadRemediationItems = useCallback(async (planId: string) => {
    if (!planId) return;
    
    const now = Date.now();
    const isCacheValid = cache.current[planId] && (now - lastFetchTime < FETCH_INTERVAL);
    
    if (isCacheValid) {
      setRemediationItems(cache.current[planId]);
      return;
    }

    setIsLoading(true);
    setError(null);
    
    try {
      const items = await getRemediationItems(planId);
      // 更新缓存
      cache.current[planId] = items;
      setLastFetchTime(now);
      setRemediationItems(items);
    } catch (err) {
      console.error(`Failed to load remediation items for plan ${planId}:`, err);
      const error = err instanceof Error ? err : new Error('Failed to load items');
      setError(error);
      // 如果请求失败但有缓存，使用缓存
      if (cache.current[planId]) {
        setRemediationItems(cache.current[planId]);
      }
      throw error; // 向外抛出错误
    } finally {
      setIsLoading(false);
    }
  }, [lastFetchTime]);

  // 当planId变化时，加载对应的整改项数据
  useEffect(() => {
    if (planId) {
      loadRemediationItems(planId);
    } else {
      setRemediationItems([]);
    }
  }, [planId, loadRemediationItems]);
  
  // 筛选出需要整改的检查项
  const pendingComplianceItems = useMemo(() => {
    return Array.isArray(complianceItems) 
      ? complianceItems.filter(item => item && item.progress_status === ProgressStatus.REMEDIATION)
      : [];
  }, [complianceItems]);
  
  // 计算统计数据
  const stats: RemediationStats = useMemo(() => {
    console.log('remediationItems', remediationItems);
    if (!remediationItems) return {
      total: 0,
      inProgress: 0,
      completed: 0,
      highRisk: 0,
    };
    return {
      total: remediationItems.length,
      inProgress: remediationItems.filter(item => item.status === RemediationStatus.IN_PROGRESS).length,
      completed: remediationItems.filter(item => item.status === RemediationStatus.COMPLETED).length,
      highRisk: remediationItems.filter(item => item.riskLevel === RiskLevel.HIGH).length,
    };
  }, [remediationItems]);
  
  // 根据筛选条件过滤整改项
  const filteredItems = useMemo(() => {
    const filtered = remediationItems.filter(item => {
      // 状态筛选
      if (filters.status !== 'all' && item.status !== filters.status) {
        return false;
      }
      
      // 风险等级筛选
      if (filters.riskLevel !== 'all' && item.riskLevel !== filters.riskLevel) {
        return false;
      }
      
      // 搜索关键词筛选
      if (filters.searchTerm) {
        const searchLower = filters.searchTerm.toLowerCase();
        return (
          item.title.toLowerCase().includes(searchLower) ||
          item.suggestion.toLowerCase().includes(searchLower)
        );
      }
      
      return true;
    });
    return sortComplianceItems(filtered);
  }, [remediationItems, filters]);
  
  // 添加整改项
  const handleAddRemediationItem = async (data: RemediationFormData) => {
    try {
      if (!data.plan_id) {
        data.plan_id = planId!;
      }
      const newItem = await addRemediationItem(data);
      if (newItem) {
        // 更新缓存
        if (data.plan_id && cache.current[data.plan_id]) {
          cache.current[data.plan_id] = [...cache.current[data.plan_id], newItem];
        }
        setRemediationItems(prev => [...prev, newItem]);
      }
      return newItem; // 返回新创建的项目
    } catch (error) {
      const err = error instanceof Error ? error : new Error('Failed to add remediation item');
      setError(err);
      showMessage('error', err.message);
      throw err; // 向外抛出错误
    }
  };
  
  // 更新整改项
  const handleUpdateRemediationItem = async (id: string, updates: Partial<RemediationItem>) => {
    try {
      const item = remediationItems.find(item => item.id === id);
      if (!item) {
        const error = new Error(`Remediation item with id ${id} not found`);
        setError(error);
        throw error;
      }
      
      // 确保更新时间字段存在
      const updatesWithTimestamp = { 
        ...updates, 
        updatedAt: new Date().toISOString() 
      };
      
      const updatedItem = await updateRemediationItem(id, updatesWithTimestamp);
      if (updatedItem) {
        // 更新缓存
        if (item.plan_id && cache.current[item.plan_id]) {
          cache.current[item.plan_id] = cache.current[item.plan_id].map(item => 
            item.id === id ? updatedItem : item
          );
        }
        
        setRemediationItems(prev => 
          prev.map(item => item.id === id ? updatedItem : item)
        );
        return updatedItem; // 返回更新后的项目
      }
    } catch (error) {
      const err = error instanceof Error ? error : new Error('Failed to update remediation item');
      setError(err);
      showMessage('error', err.message);
      throw err; // 向外抛出错误
    }
  };
  
  // 删除整改项
  const handleDeleteRemediationItem = async (id: string) => {
    try {
      // 找到要删除项的plan_id
      const itemToDelete = remediationItems.find(item => item.id === id);
      if (!itemToDelete) {
        const error = new Error(`Remediation item with id ${id} not found`);
        setError(error);
        throw error;
      }
      
      const success = await deleteRemediationItem(id, itemToDelete.plan_id);
      if (success) {
        // 更新缓存
        if (itemToDelete.plan_id && cache.current[itemToDelete.plan_id]) {
          cache.current[itemToDelete.plan_id] = cache.current[itemToDelete.plan_id].filter(
            item => item.id !== id
          );
        }
        
        setRemediationItems(prev => prev.filter(item => item.id !== id));
        return true; // 返回删除成功
      }
      return false; // 返回删除失败
    } catch (error) {
      const err = error instanceof Error ? error : new Error('Failed to delete remediation item');
      setError(err);
      showMessage('error', err.message);
      throw err; // 向外抛出错误
    }
  };
  
  // 切换整改项状态
  const handleToggleStatus = async (id: string) => {
    try {
      // 找到要切换状态项的plan_id
      const itemToToggle = remediationItems.find(item => item.id === id);
      if (!itemToToggle) {
        const error = new Error(`Remediation item with id ${id} not found`);
        setError(error);
        throw error;
      }
      
      // 使用专门的状态切换API
      const updatedItem = await toggleRemediationStatus(itemToToggle);
      if (updatedItem) {
        // 更新缓存
        if (itemToToggle.plan_id && cache.current[itemToToggle.plan_id]) {
          cache.current[itemToToggle.plan_id] = cache.current[itemToToggle.plan_id].map(item => 
            item.id === id ? updatedItem : item
          );
        }
        
        setRemediationItems(prev => 
          prev.map(item => item.id === id ? updatedItem : item)
        );
        return updatedItem; // 返回更新后的项目
      }
    } catch (error) {
      const err = error instanceof Error ? error : new Error('Failed to toggle remediation status');
      setError(err);
      showMessage('error', err.message);
      throw err; // 向外抛出错误
    }
  };
  
  // 从检查项创建整改项表单数据
  const handleCreateFromComplianceItem = (complianceItem: ComplianceItem, plan_id: string): RemediationFormData => {
    return createFormData(complianceItem, plan_id);
  };
  
  // 更新筛选条件
  const handleSetFilters = (newFilters: Partial<RemediationFilters>) => {
    setFilters(prev => ({ ...prev, ...newFilters }));
  };
  
  // 导出报告
  const handleExportReport = () => {
    if (remediationItems.length === 0) {
      showMessage('error', '没有可导出的整改项');
      return;
    }
    
    try {
      if (!assessmentType || !businessName) {
        showMessage('warning', '请刷新页面重新尝试');
        return;
      }
      const assessmentName = getAssessmentTypeName(assessmentType);
      const filename = `${businessName}-${assessmentName}-整改补充报告`;
      const sortedItems = sortComplianceItems(remediationItems);
      exportRemediationItemsToReport(sortedItems, filename);
      showMessage('success', '整改报告导出成功');
    } catch (error) {
      const err = error instanceof Error ? error : new Error('导出报告失败');
      setError(err);
      showMessage('error', err.message);
    }
  };
  
  // 使用useMemo优化contextValue，避免不必要的重渲染
  const contextValue: RemediationContextType = useMemo(() => ({
    remediationItems,
    pendingComplianceItems,
    stats,
    filters,
    setFilters: handleSetFilters,
    filteredItems,
    loadRemediationItems,
    addRemediationItem: handleAddRemediationItem,
    updateRemediationItem: handleUpdateRemediationItem,
    deleteRemediationItem: handleDeleteRemediationItem,
    toggleStatus: handleToggleStatus,
    createFromComplianceItem: handleCreateFromComplianceItem,
    exportReport: handleExportReport,
    isLoading,
    error
  }), [
    remediationItems, 
    pendingComplianceItems, 
    stats, 
    filters, 
    filteredItems, 
    isLoading, 
    error,
    handleSetFilters,
    loadRemediationItems,
    handleAddRemediationItem,
    handleUpdateRemediationItem,
    handleDeleteRemediationItem,
    handleToggleStatus,
    handleCreateFromComplianceItem,
    handleExportReport
  ]);
  
  return (
    <RemediationContext.Provider value={contextValue}>
      {children}
    </RemediationContext.Provider>
  );
};

/**
 * 使用整改台账上下文的钩子
 */
export const useRemediation = (): RemediationContextType => {
  const context = useContext(RemediationContext);
  if (context === undefined) {
    throw new Error('useRemediation must be used within a RemediationProvider');
  }
  return context;
};
